package com.ivan.stu.notetool.ImageEdit;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;


import com.ivan.stu.notetool.R;
import com.ivan.stu.notetool.model.NotifyFinishEvent;
import com.ivan.stu.notetool.utils.ActivityCollectorUtils;
import com.ivan.stu.notetool.utils.DateUtils;
import com.ivan.stu.notetool.utils.EditTextUtil;
import com.ivan.stu.notetool.utils.Global;
import com.ivan.stu.notetool.utils.ImageUtil;
import com.ivan.stu.notetool.utils.NoteToolManager;
import com.ivan.stu.notetool.utils.TextViewUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by felix on 2017/11/14 下午2:26.
 */




public class IMGEditActivity extends IMGEditBaseActivity {

    private static final int MAX_WIDTH = 1024;

    private static final int MAX_HEIGHT = 1024;

    public static final String EXTRA_IMAGE_URI = "IMAGE_URI";

    public static final String EXTRA_IMAGE_SAVE_PATH = "IMAGE_SAVE_PATH";

    @Override
    public void onCreated() {

    }

    public static void openEditor(Activity activity,String path,String savaPath){

        activity.startActivityForResult(
                new Intent(activity, IMGEditActivity.class)
                        .putExtra(IMGEditActivity.EXTRA_IMAGE_URI, path)
                        .putExtra(IMGEditActivity.EXTRA_IMAGE_SAVE_PATH,savaPath),

                2);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void notifyFinish(NotifyFinishEvent event){

        if (event.getFinishSigin() == 1){

            finish();
        }

    }

    @Override
    public void getBitmap() {

        if (!EventBus.getDefault().isRegistered(this)) {

            EventBus.getDefault().register(this);

        }

      //      ActivityCollectorUtils.addActivity(this);

        Intent intent = getIntent();
        String file = intent.getStringExtra(EXTRA_IMAGE_URI);

        if (file!=null){

            flag = 0;

      //      Log.e("path",file+"");
            ImageUtil.getBitmaoByPath(file, new ImageUtil.ImageCallBack() {
                @Override
                public void onFinish(final Bitmap bitmap) {

                    Global.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            if (bitmap != null) {
                                setContentView(R.layout.image_edit_activity);
                                initViews();
                                mImgView.setImageBitmap(bitmap);

                                onCreated();
                            } else finish();

                        }
                    });
                }
            });
        }else {  //手写画板

            //读取资源目录里面的背景图片

            flag = 1;

            Bitmap bitmap=BitmapFactory.decodeResource(getResources(), R.mipmap.notetool_bg_white);

            if (bitmap != null) {
                setContentView(R.layout.image_edit_activity);
                initViews();
                mImgView.setImageBitmap(bitmap);
                onCreated();
            } else {

                setResult(100);
                finish();
            }

        }
    }

    @Override
    public void onText(IMGText text) {
        mImgView.addStickerText(text);
    }

    @Override
    public void onModeClick(IMGMode mode) {
        IMGMode cm = mImgView.getMode();

        if (cm == mode) {

            mode = IMGMode.HIDE_BUT_DRAW;   //之前是none

        }


        mImgView.setMode(mode);
        updateModeUI();

        if (mode == IMGMode.CLIP) {
            setOpDisplay(OP_CLIP);
        }
    }

    @Override
    public void onUndoClick() {
        IMGMode mode = mImgView.getMode();
        if (mode == IMGMode.DOODLE || mode == IMGMode.SIZE || mode == IMGMode.PIC || mode == IMGMode.HIDE_BUT_DRAW) {
            mImgView.undoDoodle();
        } else if (mode == IMGMode.MOSAIC) {
            mImgView.undoMosaic();
        }
    }

    @Override
    public void onCancelClick() {
        finish();

    }

    @Override
    public void onDoneClick() {
        String path = getIntent().getStringExtra(EXTRA_IMAGE_SAVE_PATH);
        if (!TextUtils.isEmpty(path)) {
            Bitmap bitmap = mImgView.saveBitmap();
            if (bitmap != null) {
                FileOutputStream fout = null;
                try {
                    fout = new FileOutputStream(path);

                    //可能是质量压缩导致的图片失真，设置为100表示不进行质量压缩
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout);

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } finally {
                    if (fout != null) {
                        try {
                            fout.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                setResult(RESULT_OK);
                finish();
                return;
            }
        }
        setResult(RESULT_CANCELED);
        finish();
    }

    @Override
    public void onCancelClipClick() {
        mImgView.cancelClip();
        setOpDisplay(mImgView.getMode() == IMGMode.CLIP ? OP_CLIP : OP_NORMAL);
    }

    @Override
    public void onDoneClipClick() {
        mImgView.doClip();
        setOpDisplay(mImgView.getMode() == IMGMode.CLIP ? OP_CLIP : OP_NORMAL);
    }

    @Override
    public void onResetClipClick() {
        mImgView.resetClip();
    }

    @Override
    public void onRotateClipClick() {
        mImgView.doRotate();
    }

    @Override
    public void onRecoverClick() {

        //回复回撤之前的操作和视图

        IMGMode mode = mImgView.getMode();
        if (mode == IMGMode.DOODLE || mode == IMGMode.SIZE || mode == IMGMode.PIC || mode == IMGMode.HIDE_BUT_DRAW) {

            mImgView.recoverDoodle();

        } else if (mode == IMGMode.MOSAIC) {

            mImgView.recoverMosaic();
        }
    }

    @Override
    public void onNotify() {



        TextViewUtils.showToast(this,1,"该模式下暂不支持切换图片功能");

        //  Toast.makeText(getApplicationContext(),"该模式下暂不支持切换图片功能",Toast.LENGTH_SHORT);

    }

    @Override
    public void onColorChanged(int checkedColor) {

    //    Log.e("aaaaaaaaaa","onColorChanged");
        mImgView.setPenColor(checkedColor);
    }

    @Override
    public void onPenSizeChanged(float radius,int color) {

   //     Log.e("aaaaaaaaaa","onPenSizeChanged");

   //     Log.e("radius",radius+"");

        if (mImgView.getMode() == IMGMode.MOSAIC){
            //设置马赛克笔的大小


        }else {

            mImgView.setPenSize(radius);
        }


      //  mImgView.setPenColor(color);
    }

    @Override
    public void onRedoClick() {

        mImgView.redoDoodle();
        mImgView.redoMosaic();
        mImgView.redoSticker();
    }


    //更换画板图片

    @Override
    public void onImageClick(int position, int resourceId) {

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),resourceId);

        if (bitmap!=null){

            mImgView.setImageBitmap(bitmap);
        }

    }

    @Override
    public void onChoosePicClick() {

        //打开系统相册
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 0){

            if (resultCode == RESULT_OK){

                final Uri uri = data.getData();
                String[] pojo = {MediaStore.Images.Media.DATA};
                Cursor cursor = managedQuery(uri, pojo, null, null, null);
                if (cursor != null) {

                    int colunm_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    cursor.moveToFirst();
                    String path = cursor.getString(colunm_index);
                    final File file = new File(path);

                    ImageUtil.getBitmaoByPath(file.getAbsolutePath(), new ImageUtil.ImageCallBack() {
                        @Override
                        public void onFinish(final Bitmap bitmap) {

                            Global.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {

                                    if (bitmap!=null){

                                        mImgView.setImageBitmap(bitmap);
                                        mAdapter.resetPosition();

                                    }else {

                                        TextViewUtils.showToast(IMGEditActivity.this,0,"加载图片失败！");

                                    }
                                }
                            });

                        }
                    });

                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);
    }
}
